package com.duyi.controller;

import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
public class HelloController {


    @RequestMapping("/test")
    @ResponseBody
    public String test(String name, Integer age) {

        if (age == 1) {
            System.out.println(1 / 0);
        } else {
            throw new MyException("自定义异常");
        }

        return "hello springmvc!!!" + name + ",age = " + age;
    }

    // 返回字符串
    @RequestMapping("/demo1")
    @ResponseBody
    public String demo1(String name, Integer age) {

        return "hello springmvc!!!" + name + ",age = " + age;
    }


    @RequestMapping("/demo2")
    public String demo2(String name, Integer age, HttpServletRequest request) {

        request.setAttribute("name", name);
        request.setAttribute("age", age);

        return "hello";
    }

    @RequestMapping("/demo3")
    public String demo3(String name, Integer age, Model model) {

        model.addAttribute("name", name);
        model.addAttribute("age", age);

        return "hello";
    }

    // restful 请求格式

    @RequestMapping("/demo4")
    public ModelAndView demo4(String name, Integer age) {
        ModelAndView mv = new ModelAndView();


        mv.setViewName("hello");
        mv.addObject("name", name);
        mv.addObject("age", age);

        return mv;
    }


    // 返回字符串
    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {

        return "hello springmvc!!!";
    }

    //    返回JSP页面
    @RequestMapping("/hello2")
    public String helloJsp() {


//        try {
//            Thread.sleep(10000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

//        <!-- 前缀 -->
//        <property name="prefix" value="/WEB-INF/jsp/"></property>
//        <!-- 后缀 -->
//        <property name="suffix" value=".jsp"></property>
        // /WEB-INF/jsp/hello.jsp
        return "hello";
    }

}
